CCK Allowed Values List, PHP code and hook_content_allowed_values_alter()

Wooo, catchy blog post title eh?

It's good to keep PHP code out of your Drupal database right?

The flexibility afforded by adding PHP code to things like your "Allowed values list" for a CCK field is absolutely fantastic on one hand but niggles me on the other because the code ends up in the database and won't be version controlled.

"Create a module, implement hook_form_alter() and set the #options for the form element..." I hear you cry!!! I did try this but it doesn't actually work, I need to spend some more time working out exactly why.

Anyhow, whilst I was poking around with this on a Drupal 6 site I came across a hook in CCK's content.module:

  // Allow external modules to translate allowed values list.
  drupal_alter('content_allowed_values', $allowed_values[$cid], $field);

In eager anticipation I implemented the hook like so:

/**
 * Implementation of hook_content_allowed_values_alter().
 */
function mymodule_content_allowed_values_alter(&$allowed_values, $field) {
  // Display user roles as options.
  if ($field['field_name'] == 'field_test') {
    $options = user_roles(TRUE);
    unset($options[DRUPAL_AUTHENTICATED_RID]);
    $allowed_values = $options;
  }
}

And it works...

So, is anyone else using this hook for this purpose? Can you see any problems with this approach?

Comments

Hey, I've actually been coding around this... I was altering the cck modules and getting a (if function exists) and then call my own function to override the values. Never knew this existed until I've found your blog. Shame on me, and thanks!

Miguel

Well spotted, though whether or not it gets called may be field dependent.

http://drupal.org/node/780566

Please forgive the ignorance. This function is native drupal?
Curso de webdesign|
Grafiato|
|curso de php|

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.