I was previously using the Default Value PHP field in the CCK Field Properties page to define multi-value default which was working fine. However the code is now getting so complex and I need to pass arguments to it that developing it within the CMS is becoming unfeasible, so I'd like to move the functionality out to a custom module.

I'm successfully using hook_form_alter to set defaults for single value CCK fields, so this isn't a problem. What I'm curious about is that when $form is passed to hook_form_alter, only the first element (0 or $form['field_myfield'][0]) exists, whilst I need to have from 0 to x default values.

Is the best practice simply to clone element 0 for as many default values as I need? Or is there another hook I should be using to set the initial number of empty fields before setting the defaults or something else I'm not thinking of?

Thanks :D

1 Answer 1


I think you may need to use #after_build, to ensure that your alter code runs after CCK has completely built the form element. Try something like this

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['field_myfield']['#after_build'][] = 'mymodule_after_build';

function mymodule_after_build(&$form_element, &$form_state) {
  // Have a look at the element with devel's dsm

  // Code to adjust your form element here...

  return $form_element;

I'm not 100% on the above syntax. I'd sugest you have a look at this article entitled hook_form_alter() and CCK fields

  • 2
    You should add your function to the after build list, not override it, like this $form['field_myfield']['#after_build'][] = 'mymodule_after_build'; but other than that, this is probably the way to go. And yes, if you have multiple default values, you will probably have to create the necessary form elements yourself, not sure.
    – Berdir
    May 18, 2011 at 11:12
  • Good catch on appending vs overriding - you need to make sure you don't wipe out any after_build hooks that may have been added by other modules. May 18, 2011 at 11:56
  • 1
    You need to return the form element in the after build function or the form element won't appear.
    – AKS
    Dec 12, 2012 at 23:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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