Setting CCK Option Selects to Blank as Default and Required

This took me a little bit of poking around to figure out, so here's a quick tip in case others are attempting to do the same thing.

For some CCK select options, you want it to both be required and to also not default on the first answer because a user might click through without changing the default without meaning to. There is the Default value options you can play with, but the easiest way I've found is in your Allowed values list you can simply enter this as your first choice:

|-Please Choose-

This will give you the -Please Choose- as a default, but if the user doesn't switch it, an error will come up. The reason for this is it's expecting you to have your answer in a format such as 1|Option 1, with the "machine" or "key" name first, followed by a pipe, and then the name of the option a user will see. If you don't give it a machine name it simply isn't valid.

Here's an example of an Allowed values list you might have.

|- Choose City-
la|Los Angeles
sd|San Diego
sf|San Francisco
sb|Santa Barbara

Please note that for normal options you don't have to have the key value at all. This isn't the best way to do this, as it now gives you a value without a key which can be troublesome later.

Alternatively, you could use hook_nodeapi. For example, let's say you add in your CCK field

choose|-Choose-

Now, in a custom module, in this case called "siteconfig", you could add:

<?php
function siteconfig_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  if (
$node->type == 'custom_content_type') {
    switch (
$op) {
      case
'validate':
        if (
$node->field_city[0]['value'] == 'choose') {
         
form_set_error('field_city', 'Invalid choice, please choose a city.');
        }
      break;
    }
  }
}
?>

Tags:

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <b> <address> <blockquote> <br> <caption> <center> <code> <dd> <del> <div> <dl> <dt> <em> <font> <h2> <h3> <h4> <h5> <h6> <hr> <i> <img> <li> <ol> <p> <pre> <span> <strong> <sub> <sup> <table> <tbody> <td> <tfoot> <th> <thead> <tr> <u> <ul> <tr>
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".
  • Use the special tag [adsense:format:group:channel] or [adsense:block:location] to display Google AdSense ads.

More information about formatting options

To combat spam, please enter the code in the image.