I have a CCK form where the user selects whether they are "certified." If they are, then I want the date and state of their certification. If not, I want those fields to not show.

Comments

nancydru’s picture

I guess not?

mooffie’s picture

Project: Computed Field » Content Construction Kit (CCK)
Component: Code » General

[ I'm combining http://drupal.org/node/167413 here. ]

First, there's the cosmetic issue: hiding/showing some field(s) if/when some other field contains a certain value.

This can be done via jQuery: We can attach an "on change", or an "on click", event handler to the select box, or to a checkbox, and in this handler to toggle the visibility of the date field.

Here's the basic code:

$(function() {

  $('#id-of-field-that-changes').click(function() {
    with ($('#id-of-field-to-hide-or-show').ancestors('.form-item')) {
      $(this).is(':checked') ? show() : hide();
    }
  })
  .click(); // initialize

});

I assumed we're using a checkbox (It's much easier. Besides, I had the code ready from some forum thread. You can change the code to suit your selectbox.)

the actual need [...] is to have the field [...] required [...] based on "field_cert_status."

OK, cosmetics aside. Now we're doing "data integrity".

First we do validation. We need to implement hook_nodeapi(). A possible solution:

function mymodule_nodeapi(&$node, $op) {
  if ($node->type != 'resume') return; // 'resume' is our node-type

  if ($op == 'validate') {
    if ($node->field_cert_status[0]['value'] == 1 &&
       !$node->field_cert_date[0]['value']) {
      form_set_error('field_cert_date', t('Please fill in a date'));
    }
  }
}

Note that my 'field_cert_status' doesn't hold 'C'/'NC' but 0/1.

If we want to clear the date when 'field_cert_status == 0', then:

...
if ($op == 'submit') {
  if ($node->field_cert_status[0]['value'] == 0) {
    $node->field_cert_date[0]['value'] = '';
  }
}
...
I want to prefill "cert_date" with todays date
...
if ($op == 'prepare') {
  if ($node->field_cert_status[0]['value'] == 0) {
    $node->field_cert_date[0]['value'] = date('Y-m-d H:i:s');
  }
}
...

I'll try to put this code on my site later today.

mooffie’s picture

OK, you can see the form in action here:

http://blue.live4all.co.il/~mooffie/cms/node/add/tst

(Anonymous users have full permissions here. No need to register.)

You can download the code here:

http://blue.live4all.co.il/~mooffie/cms/sites/all/modules/support-public...

(I should have used a read date field, not a 'text' one. But I don't like the current Date API. I'm awaiting the new one.)

nancydru’s picture

Status: Active » Closed (fixed)